param(
    [string]$AppBuildDir,
    [string]$Windeployqt
)
$ErrorActionPreference = 'Stop'

function Info($m){ Write-Host "[INFO] $m" }
function Warn($m){ Write-Host "[WARN] $m" }
function Err ($m){ Write-Host "[ERROR] $m"; exit 1 }

$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
$Bin = Join-Path $Root 'bin'
$DefaultRelease = Join-Path $Root 'build/Desktop_Qt_6_8_1_MinGW_64_bit-Release/app/release'
$DefaultDebug   = Join-Path $Root 'build/Desktop_Qt_6_8_1_MinGW_64_bit-Debug/app/debug'

# Resolve build dir
if ([string]::IsNullOrWhiteSpace($AppBuildDir)) {
    if (Test-Path (Join-Path $DefaultRelease 'DesktopTimer.exe')) {
        $AppBuildDir = $DefaultRelease
        Info "Using default Release build output."
    } elseif (Test-Path (Join-Path $DefaultDebug 'DesktopTimer.exe')) {
        $AppBuildDir = $DefaultDebug
        Info "Using default Debug build output."
    } else {
        Err "DesktopTimer.exe not found in default locations. Pass build dir as -AppBuildDir."
    }
}

$AppExe = Join-Path $AppBuildDir 'DesktopTimer.exe'
if (!(Test-Path $AppExe)) { Err "DesktopTimer.exe not found: $AppExe" }

# Compute kit root (two levels up from app/release or app/debug)
function Get-KitRoot([string]$dir){
    try {
        $d = Resolve-Path $dir | % { $_.Path }
        $d = Split-Path $d -Parent  # .../app
        $d = Split-Path $d -Parent  # .../<kit>/<config>
        return $d
    } catch { return '' }
}
$KitRoot = Get-KitRoot $AppBuildDir
if ([string]::IsNullOrWhiteSpace($KitRoot)) { Warn "Unable to infer kit root; skipping module DLL copy." } else { Info "Kit root: $KitRoot" }

# Resolve windeployqt
if ([string]::IsNullOrWhiteSpace($Windeployqt)) {
    if ($env:QT_BIN) { $Windeployqt = Join-Path $env:QT_BIN 'windeployqt.exe' }
}
if (!(Test-Path $Windeployqt)) {
    $TryDefault = 'G:/Qt/6.8.1/mingw_64/bin/windeployqt.exe'
    if (Test-Path $TryDefault) { $Windeployqt = $TryDefault }
}
if (!(Test-Path $Windeployqt)) {
    $found = (Get-Command windeployqt.exe -ErrorAction SilentlyContinue | Select-Object -First 1)
    if ($found) { $Windeployqt = $found.Source }
}
if (!(Test-Path $Windeployqt)) { Err "windeployqt.exe not found. Set QT_BIN or pass -Windeployqt." }
Info "windeployqt: $Windeployqt"

# Prepare bin
Info "Preparing bin directory..."
if (Test-Path $Bin) { Remove-Item $Bin -Recurse -Force }
New-Item -ItemType Directory -Path $Bin | Out-Null
New-Item -ItemType Directory -Path (Join-Path $Bin 'resource') | Out-Null
New-Item -ItemType Directory -Path (Join-Path $Bin 'translation') | Out-Null
New-Item -ItemType Directory -Path (Join-Path $Bin 'log') | Out-Null

# Copy exe
Info "Copying DesktopTimer.exe ..."
Copy-Item -Path $AppExe -Destination (Join-Path $Bin 'DesktopTimer.exe') -Force

# Copy assets
Info "Copying static assets ..."
if (Test-Path (Join-Path $Root 'app/resource')) { Copy-Item -Recurse -Force (Join-Path $Root 'app/resource') -Destination (Join-Path $Bin 'resource') }
if (Test-Path (Join-Path $Root 'fonts'))        { Copy-Item -Recurse -Force (Join-Path $Root 'fonts')        -Destination (Join-Path $Bin 'fonts') }
if (Test-Path (Join-Path $Root 'gifs'))         { Copy-Item -Recurse -Force (Join-Path $Root 'gifs')         -Destination (Join-Path $Bin 'gifs') }
if (Test-Path (Join-Path $Root 'docs'))         { Copy-Item -Recurse -Force (Join-Path $Root 'docs')         -Destination (Join-Path $Bin 'docs') }

# Copy translations
Info "Copying translations ..."
if (Test-Path (Join-Path $Root 'app/translation')) { Copy-Item -Recurse -Force (Join-Path $Root 'app/translation') -Destination (Join-Path $Bin 'translation') }
$ts = Get-ChildItem -Path $Root -Filter 'language_*.ts' -ErrorAction SilentlyContinue
if ($ts) { Copy-Item -Force $ts.FullName -Destination (Join-Path $Bin 'translation') }

# Copy module DLLs if present
function Copy-ModuleDlls([string]$kit,[string]$cfg){
    $mods = 'log','core','module','service','components','view'
    foreach($m in $mods){
        $dll = Join-Path (Join-Path (Join-Path $kit $m) $cfg) ("$m.dll")
        if (Test-Path $dll) {
            Info "Copying $m.dll ..."
            Copy-Item -Force $dll -Destination $Bin
        }
    }
}
# infer cfg from last path segment
$cfg = Split-Path $AppBuildDir -Leaf
if ($KitRoot -and $cfg) { Copy-ModuleDlls -kit $KitRoot -cfg $cfg }

# Run windeployqt
Info "Running windeployqt ..."
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Windeployqt
$psi.ArgumentList.Add('--release')
$psi.ArgumentList.Add('--no-translations')
$psi.ArgumentList.Add((Join-Path $Bin 'DesktopTimer.exe'))
$psi.WorkingDirectory = $Root
$psi.UseShellExecute = $false
$p = [System.Diagnostics.Process]::Start($psi)
$p.WaitForExit()
if ($p.ExitCode -ne 0) { Err "windeployqt failed. exitCode=$($p.ExitCode)" }

# Ensure Qt Multimedia runtime is present (some builds may not be auto-detected)
try {
    $qtBin = Split-Path $Windeployqt -Parent
    $qtRoot = Split-Path $qtBin -Parent  # .../mingw_64
    $qtPlugins = Join-Path $qtRoot 'plugins'

    $extraDllPatterns = @('Qt6Multimedia*.dll','Qt6StateMachine*.dll')
    foreach($pat in $extraDllPatterns){
        $dlls = Get-ChildItem -Path $qtBin -Filter $pat -ErrorAction SilentlyContinue
        if ($dlls) {
            foreach($d in $dlls){
                if (!(Test-Path (Join-Path $Bin $d.Name))) {
                    Info "Copying $($d.Name) ..."
                    Copy-Item -Force $d.FullName -Destination $Bin
                }
            }
        }
    }

    $srcMmPlugins = Join-Path $qtPlugins 'multimedia'
    $dstPluginsRoot = Join-Path $Bin 'plugins'
    $dstMmPlugins = Join-Path $dstPluginsRoot 'multimedia'
    if (Test-Path $srcMmPlugins) {
        if (!(Test-Path $dstMmPlugins)) { New-Item -ItemType Directory -Path $dstMmPlugins -Force | Out-Null }
        Info "Copying multimedia plugins ..."
        Copy-Item -Recurse -Force $srcMmPlugins\* $dstMmPlugins
    }
} catch {
    Warn "Post-copy Multimedia step skipped: $($_.Exception.Message)"
}

Info "Packaging completed. Output: $Bin"
exit 0
